package com.maben.mqtt.test002;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * 简单发送端
 */
public class Publish {
    public static void main(String[] args) throws Exception {
        final String broker = "tcp://127.0.0.1:1883";
        final String clientId = "publish_client";
        final String topic = "mqtt_test";
        final String username = "emqx";
        final String password = "public";
        /*
            QoS 0：消息最多传递一次，如果当时客户端不可用，则会丢失该消息。
            QoS 1：消息传递至少 1 次。
            QoS 2：消息仅传送一次。
         */
        int qos = 2;
        //设置连接客户端
        MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence());
        // 设置连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(60);
        options.setKeepAliveInterval(60);
        // 连接
        client.connect(options);

        /*
        retain为true
        一个主题下最新一条保留消息会驻留在消息服务器，后来的订阅者订阅主题时仍可以接收该消息
        但是会存在一个问题，订阅者每次启动都会收到这条已保留的信息，会造成重复消息。
         */
//        message.setRetained(false);


        // 发布消息
        for (int i = 0; i < 50_0000; i++) {
            // 创建消息并设置 QoS
            final String content = i + "";
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            client.publish(topic, message);
            System.out.println("Message published:" + content);
        }
        // 关闭连接
        client.disconnect();
        // 关闭客户端
        client.close();
    }
}
